package com.bwie.car.service.impl;

import com.bwie.car.mapper.CarMapper;
import com.bwie.car.service.CarService;
import com.bwie.common.domain.Car;
import com.bwie.common.domain.request.CarRequest;
import com.bwie.common.result.PageResult;
import com.bwie.common.result.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public Result<PageResult<Car>> showCar(CarRequest carRequest) {
        PageHelper.startPage(carRequest.getPageNum(),carRequest.getPageSize());

        List<Car> carList = carMapper.showCar(carRequest);
        PageInfo<Car> info = new PageInfo<>(carList);

        return PageResult.toResult(info.getTotal(),carList);
    }

    @Override
    public Result findById(String carId) {
        Car byId = carMapper.findById(carId);
        return Result.success(byId);
    }

    @Override
    public Result reply(Integer carId) {
        Car car = new Car();
        Car byGrade = carMapper.findByGrade(carId);
        if(byGrade.getGrade()<car.getGrade()){
            return Result.error("芝麻信用分不足");
        }
        if(byGrade.getGrade()>car.getGrade()){
            return Result.error("贷款成功");
        }
        rabbitTemplate.convertAndSend("sendMsg",message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replace("-",""));
            return message;
        });
        return Result.success(byGrade);
    }


}
